package com.zyh.server.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyh.server.config.Constant;
import com.zyh.server.entity.Order;
import com.zyh.server.entity.User;
import com.zyh.server.service.OrderService;
import com.zyh.server.utils.R;
import com.zyh.server.utils.RedisUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @Author: zyh
 * @Date: 2024-11-19-9:38
 * @Description
 */
@Tag(name = "订单模块")
@Slf4j
@RestController //@Controller + @ResponseBody后端传递json数据
@RequestMapping("/order")
@CrossOrigin(origins = "*") //允许跨域请求
public class OrderController {

	@Autowired
	private OrderService orderService;
	@Autowired
	private RedisUtil redisUtil;

	/**
	 * 秒杀商品的方法
	 *
	 * @param token
	 * @param orderId
	 *
	 * @return
	 */
	@Operation(summary = "获取用户信息")
	@Parameters({
			@Parameter(name = "token", description = "用户token", in = ParameterIn.HEADER),
			@Parameter(name = "orderId", description = "订单编号", in = ParameterIn.QUERY)
	})
	@GetMapping("/orderDetails")
	public R orderDetails(
			@RequestHeader("token") String token,
			@RequestParam("orderId") String orderId) {
		log.info("获取用户信息，token:{}, orderId:{}", token, orderId);
		// 1. 获取order对象
		Order order = orderService.getOrderById(orderId);
		if (Objects.nonNull(order)) {
			// 从redis中获取用户信息
			Object obj = redisUtil.getObj(Constant.REDIS_TOKEN_PREFIX + token);
			User user = new ObjectMapper().convertValue(obj, User.class);
			log.info("user值：{}", user);
			order.setUser(user);
			return R.ok().setData(order);
		}
		return R.fail().setMsg("订单不存在！");
	}

	@Operation(summary = "获取用户自己的订单列表")
	@Parameters({
			@Parameter(name = "token", description = "用户token", in = ParameterIn.HEADER)
	})
	@GetMapping("/list")
	public R getOrderList(@RequestHeader("token") String token) {
		// 根据请求头的token值从redis中获取用户信息
		Object obj = redisUtil.getObj(Constant.REDIS_TOKEN_PREFIX + token);
		if (Objects.isNull(obj)) {
			return R.fail().setMsg("token值失效");
		}
		User user = new ObjectMapper().convertValue(obj, User.class);
		// 获取用户id
		Integer userId = user.getId();
		// 根据用户id查询订单列表
		List<Order> orderListByUserId = orderService.findOrderListByUserId(userId);
		return R.ok().setData(orderListByUserId);
	}
}
